package com.ljs.springbootinit.controller;

import cn.hutool.json.JSONUtil;
import com.ljs.springbootinit.config.ThreadPoolExecutorConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/queue")
@Slf4j
/**
 * 任务队列Controller
 */
public class QueueController {
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("/add")
    public void addQueue(String queueName) {
        CompletableFuture.runAsync(() -> {
            log.info("任务执行中:" + queueName+".执行人"+Thread.currentThread().getName());
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, threadPoolExecutor);
    }
    @GetMapping("/get")
    public String getQueue( ){
        Map<String, Object> map = new HashMap<>();
        int poolSize = threadPoolExecutor.getPoolSize();
        map.put("线程池的大小", poolSize);
        long taskCount = threadPoolExecutor.getTaskCount();
        map.put("任务总数",taskCount);
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        map.put("已完成的任务数", completedTaskCount);
        int workQueueSize = threadPoolExecutor.getQueue().size();
        map.put("任务在排队中的数", workQueueSize);
        int activeCount = threadPoolExecutor.getActiveCount();
        map.put("正在执行的任务数or当前正在使用的线程数", activeCount);
        return JSONUtil.toJsonStr(map);
    }
}
